<script setup>
import {ref} from "vue";
import {Lock, User} from "@element-plus/icons-vue";
import {baseURL} from "@/utils/request.js";
import instance from "@/utils/request.js";
import {useRouter} from 'vue-router'
import {ElMessage} from "element-plus";
import {useUserStore} from "@/store/modules/student/index.js";

//用于检验表单数据
const dataFormRef = ref()
//标记是否为注册
const isRegister = ref(false)
const loginForm = ref({
  userName: '',
  userPassword: '',
  userRole: '',
  rePassword: '',
})
const registerForm = ref({
  userName: '',
  userPassword: '',
  userRole: '',
})

//检查密码是否一致
const checkRePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次确认密码'))
  } else if (value !== registerForm.value.userPassword) {
    callback(new Error('请确保两次输入的密码一样'))
  } else {
    callback()
  }
}

//定义表单规则
const rules = {
  userName: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 3, max: 10, message: '长度在 3 到 12 个字符', trigger: 'blur'}
  ],
  userPassword: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, max: 20, message: '长度在 6 到 15 个字符', trigger: 'blur'}
  ],
  rePassword: [
    {required: true, message: '请再次输入密码', trigger: 'blur'},
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15的非空字符',
      trigger: 'blur'
    },
    {validator: checkRePassword, trigger: 'blur'}
  ]
}

const router = useRouter()
const userStore = useUserStore()

const login = async () => {
  //等待表单校验
  await dataFormRef.value.validate()
  const param = {
    userName: loginForm.value.userName,
    userPassword: loginForm.value.userPassword,
    userRole: loginForm.value.userRole
  }
  //向后端发送请求
  instance.post(baseURL + '/login', param).then(res => {
    //登入成功
    if(res.data.flag){
      let role = res.data.data.userRole
      userStore.userInfo = res.data.data
      //0表示学生
      if(role==="0"){
        ElMessage.success('登录成功')
        setTimeout(3000)
        //路由到学生主页面
        router.push('/student')

      }else{
        ElMessage.success('登录成功')
        setTimeout(3000)
        //路由到老师主页面
        router.push('/teacher')
      }
    }else{
      ElMessage.error('登录失败')
      router.push('/')
    }
  })
}
const clearLoginForm = ()=>{
  loginForm.value = {
    userName: '',
    userPassword: '',
    userRole: '',
  }
}

const clearRegisterForm = ()=>{
  registerForm.value = {
    userName: '',
    userPassword: '',
    userRole: '',
    rePassword: '',
  }
}

const register = async () => {

  await dataFormRef.value.validate()
  const param = {
    userName: registerForm.value.userName,
    userPassword: registerForm.value.userPassword,
    userRole: registerForm.value.userRole
  }

  instance.post(baseURL + '/register', param).then(res => {

    if(res.data.flag){
      ElMessage.success('注册成功,即将返回登入页面！')
      setTimeout(3000)
      clearLoginForm()
      //修改注册状态
      isRegister.value = false
      router.push('/')
    }else{
      ElMessage.error('注册失败')
      setTimeout(3000)
      clearRegisterForm()
    }
  })
}

</script>

<template>
  <div class="container">
    <div class="login-wrapper">
      <div class="item">
        <div style="font-size: 20px;font-weight:bolder;font-style: italic">
          高校选课管理系统
        </div>
      </div>
      <el-form :model="loginForm" ref="dataFormRef" v-if="!isRegister" :rules="rules" status-icon class="form-wrapper">
        <el-form-item prop="userName">
          <el-input v-model="loginForm.userName" placeholder="请输入用户名" style="width: 450px;height: 40px;">
            <template #prefix>
              <el-icon>
                <User/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="userPassword">
          <el-input type="password" v-model="loginForm.userPassword" placeholder="请输入密码"
                    style="width: 450px;height: 40px;"
                    show-password>
            <template #prefix>
              <el-icon>
                <Lock/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="userRole">
          <el-radio-group v-model="loginForm.userRole">
            <el-radio v-model="loginForm.userRole" value="0">学生</el-radio>
            <el-radio v-model="loginForm.userRole" value="1">教师</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login">登录</el-button>
          <el-button type="primary" @click="isRegister=true">注册</el-button>
        </el-form-item>
      </el-form>

      <!--注册表单-->
      <el-form :model="registerForm" ref="dataFormRef" v-else :rules="rules" status-icon class="form-wrapper">
        <el-form-item prop="userName">
          <el-input v-model="registerForm.userName" placeholder="请输入用户名" style="width: 450px;height: 40px;">
            <template #prefix>
              <el-icon>
                <User/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="userPassword">
          <el-input type="password" v-model="registerForm.userPassword" placeholder="请输入密码"
                    style="width: 450px;height: 40px;"
                    show-password>
            <template #prefix>
              <el-icon>
                <Lock/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="rePassword">
          <el-input type="password" v-model="registerForm.rePassword" placeholder="请再次输入密码"
                    style="width: 450px;height: 40px;">
            <template #prefix>
              <el-icon>
                <Lock/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="userRole">
          <el-radio-group v-model="registerForm.userRole">
            <el-radio v-model="registerForm.userRole" value="0">学生</el-radio>
            <el-radio v-model="registerForm.userRole" value="1">教师</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="register">注册</el-button>
          <el-button type="primary" @click="isRegister=false">返回</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-image: url("@/assets/img/R-C.jpg");
  background-size: cover;
  background-position: center;
}

.login-wrapper {
  width: 100%;
  max-width: 450px;
  padding: 40px;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  background-color: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}

.login-wrapper:hover {
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
}

.item {
  text-align: center;
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.form-wrapper {
  width: 100%;
}

.el-input {
  width: 450px; /* 将输入框宽度设置为100%以填满容器 */
  height: 40px;
}

.el-form-item {
  margin-bottom: 24px;
}

.el-button {
  width: 100%;
  margin-top: 10px;
}

/* Add some spacing between buttons */
.el-button + .el-button {
  margin-left: 0;
  margin-top: 10px;
}

/* Style the radio buttons */
.el-radio-group {
  display: flex;
  justify-content: space-between;
}

.el-radio {
  width: 48%;
}

/* Style the input prefix icons */
.el-input__prefix {
  color: #666;
}

/* Style the input field */
.el-input {
  --el-input-focus-border-color: #409eff;
}

</style>
